package com.ja.openchat.viewmodels;

import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.google.gson.JsonObject;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.chat.PreviewWebViewActivity;
import com.ja.openchat.ui.me.MyAlbumFragment;
import com.ja.openchat.ui.me.SayHelloFragment;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.circle.BlogListInfo;
import com.zy.openchat.core.model.circle.BlogUserInfo;
import com.zy.openchat.core.model.circle.CircleVisibleType;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.user.UserFullInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.KLog;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class PersonalInformationViewModel extends BaseViewModel {
    public ObservableField<UserInfo> userAvatar = new ObservableField<>();
    public ObservableField<String> userName = new ObservableField<>();
    public ObservableField<String> userIntro = new ObservableField<>("暂无签名~");
    public ObservableField<String> entity = new ObservableField<>();
    //默认为男图标，1为女图标
    public ObservableField<Integer> position = new ObservableField<>(0);

    public ObservableField<Boolean> isSelf = new ObservableField<>(true);
    public ObservableField<String> distance = new ObservableField<>("");
    public ObservableField<Boolean> isShowSayHello = new ObservableField<>(true);
    public long mUserId;


    public PersonalInformationViewModel(@NonNull @NotNull Application application) {
        super(application);
        entity.set("测试");
    }

    //相册的点击事件
    public BindingCommand albumOnClickCommand = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putLong("userId", mUserId);
        startContainerActivity(MyAlbumFragment.class.getCanonicalName(), bundle);
    });
    //打个招呼的点击事件
    public BindingCommand hiOnClickCommand = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putLong("userId", mUserId);
        startContainerActivity(SayHelloFragment.class.getCanonicalName(),bundle);
    });
    //投诉的点击事件
    public BindingCommand complaintOnClickCommand = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putString("url", Constants.KHostEReport);
        bundle.putString("title", "投诉");
        startActivity(PreviewWebViewActivity.class, bundle);
    });

    public ObservableList<PersonalInformationItemViewModel> observableList = new ObservableArrayList<>();
    public ItemBinding<PersonalInformationItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_person_information);


    public void setData(Bundle bundle) {
        if (bundle != null) {
            mUserId = bundle.getLong("userId", UserInfo.getUserInfo().id);
            distance.set(bundle.getString("distance"));
        } else {
            mUserId = UserInfo.getUserInfo().id;
        }
        isSelf.set(UserInfo.getUserInfo().id == mUserId);
    }

    @Override
    public void onResume() {
        super.onResume();
        requestData1(0, 1);
    }

    private long currentBlogId = 0;
    private BlogUserInfo mBlogUserInfo;
    private UserFullInfo userFullInfo;

    private void requestData1(long from_blog_id, int page) {
        if (page == 1)
            from_blog_id = 0;
        if (from_blog_id == 0) {
            TelegramManager.getTelegramManager().getBlogUser(getApplication(), mUserId, new TgResultBlock<BlogUserInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, BlogUserInfo obj) {
                    mBlogUserInfo = obj;
                    loadUserInfo();
                }

                @Override
                public void onTimeout(Map<String, Object> request) {

                }
            });
        }
        TelegramManager.getTelegramManager().getUserFullInfo(getApplication(), mUserId, new TgResultBlock<UserFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserFullInfo obj) {
                userFullInfo = obj;
                loadUserInfo();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
        int limit = 20;
        if (from_blog_id == 0 && !Common.isEmpty(observableList)) {
            if (observableList.size() > 20) {
                limit = observableList.size();
            }
        }
        TelegramManager.getTelegramManager().getCircleHistory(getApplication(), new CircleVisibleType(mUserId), from_blog_id, limit, new TgResultBlock<BlogListInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, BlogListInfo obj) {
                if (obj != null) {
                    if (obj.blogs != null && obj.blogs.size() > 0)
                        currentBlogId = obj.blogs.get(obj.blogs.size() - 1).id;
                    finishRefreshAndLoad(page, obj.blogs);
                } else {
                    finishRefreshAndLoad(page, null);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                finishRefreshAndLoad(page, null);
            }
        });
    }

    private void finishRefreshAndLoad(int page, List<BlogInfo> blogs) {
        observableList.clear();
        if (blogs != null)
            for (int i = 0; i < blogs.size(); i++) {
                if (i > 2)
                    return;
                observableList.add(new PersonalInformationItemViewModel(this, blogs.get(i)));
            }
    }

    private void loadUserInfo() {
        UserInfo userInfo = UserInfo.getUserInfo(mUserId);
        if (userInfo != null) {
            userAvatar.set(userInfo);
            userAvatar.notifyChange();
            userName.set(userInfo.displayName());
            isShowSayHello.set(userInfo.canSendMsg());
        }
        if (userFullInfo != null && !TextUtils.isEmpty(userFullInfo.bio)) {
            userIntro.set(userFullInfo.bio);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(TgEvent tg_event) {
        if (tg_event == null || tg_event.data == null) {
            return;
        }
        switch (tg_event.event) {
            case EUser_Td_Message_Photo_Ok:
            case EUser_Td_Message_Video_Ok:
                if (tg_event.data instanceof FileTaskInfo && tg_event.dataEx instanceof FileInfo) {
                    FileInfo fileInfo = (FileInfo) tg_event.dataEx;
                    String ids = ((FileTaskInfo) tg_event.data).id;
                    if (!TextUtils.isEmpty(ids) && ids.contains("_")) {
                        String[] idArray = ids.split("_");
                        if (idArray.length > 1) {
                            for (int i = 0; i < observableList.size(); i++) {
                                BlogInfo blogInfo = observableList.get(i).circleInfo;
                                boolean isVideoDownedd = blogInfo.isVideoDownloadEnough();

                                if (idArray[1].equals(String.valueOf(blogInfo.id))) {
                                    switch (tg_event.event) {
                                        case EUser_Td_Message_Photo_Ok:
                                            blogInfo.updatePhotoFile(fileInfo);
                                            break;
                                        case EUser_Td_Message_Video_Ok:
                                            blogInfo.updateVideoFile(fileInfo);
                                            break;
                                    }
                                    KLog.d("update==111----" + tg_event.event + i);

                                    if (tg_event.event == TelegramManager.EUser_TgEvent.EUser_Td_Message_Video_Ok && isVideoDownedd) {
                                        return;
                                    }
//                                    KLog.d("update==" + tg_event.event + i);
//                                    observableList.set(i, new MyAlbumItemViewModel(this, blogInfo));
                                    String mediaUrl = observableList.get(i).getMediaUrl();
                                    KLog.d("update mediaUrl==  " + i + mediaUrl);
                                    break;
                                }
                            }
                        }
                    }
                }
                break;
            case EUser_Td_Delete_Blog:
                if (tg_event.data != null && tg_event.data instanceof Long) {
                    long blogId = (Long) tg_event.data;
                    for (int i = 0; i < observableList.size(); i++) {
                        if ((observableList.get(i)).circleInfo != null
                                && blogId == (observableList.get(i)).circleInfo.id) {
                            observableList.remove(i);
                            break;
                        }
                    }
                }
                break;
            case EUser_Td_Contact_Photo_Ok:
            case EUser_Td_UpdateContactInfo:
                if ((tg_event.data instanceof UserInfo)) {
                    UserInfo userInfo = (UserInfo) tg_event.data;
                    if (userInfo.id == mUserId) {
                        loadUserInfo();
                    }
                }
                break;
            case EUser_Td_Chat_User_Full_Info:
                if (tg_event.data instanceof Long) {
                    if (mUserId == ((Long) tg_event.data)) {
                        if (tg_event.dataEx != null && tg_event.dataEx instanceof UserFullInfo) {
                            userFullInfo = (UserFullInfo) tg_event.dataEx;
                            loadUserInfo();
                        }
                    }
                }
                break;
            case EUser_Td_UpdateUserInfo:
                loadUserInfo();
                break;
            case EUser_Td_update_Circle_Unread_count:
                break;

        }
    }
}
